package top.goldenyear.porpoise.dev.code.service;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import top.goldenyear.porpoise.dev.code.config.CodeConfig;
import top.goldenyear.porpoise.dev.code.dto.req.CodeGenUpdateReq;
import top.goldenyear.porpoise.dev.code.model.CodeGen;
import top.goldenyear.porpoise.dev.code.model.proxy.CodeGenProxy;
import top.goldenyear.porpoise.framework.common.model.LoginUser;
import top.goldenyear.porpoise.framework.web.core.service.BaseService;

/**
 * @author airhead
 */
@Component
public class CodeGenService extends BaseService<CodeGen, CodeGenProxy> {
  @Db private EasyEntityQuery easyEntityQuery;
  @Inject private CodeTableService codeTableService;
  @Inject private CodeColumnService codeColumnService;
  @Inject private CodeDbService codeDbService;
  @Inject private CodeConfig codegenProps;

  public CodeGenService() {
    super(CodeGen.class, CodeGenProxy.class);
  }

  public CodeGen getByAccountId(Integer accountId) {
    return entityQueryable()
        .where(
            codeGenProxy -> {
              codeGenProxy.accountId().eq(accountId);
            })
        .firstOrNull();
  }

  public CodeGen upsertCodeGen(CodeGenUpdateReq updateReq, LoginUser loginUser) {
    CodeGen codeGen = getByAccountId(loginUser.getId());
    if (codeGen == null) {
      codeGen = new CodeGen();
      codeGen.setAccountId(loginUser.getId());
      codeGen.setAuthor(loginUser.getNickName());
      fillCodeGen(updateReq, codeGen);
      save(codeGen);
    } else {
      fillCodeGen(updateReq, codeGen);
      updateById(codeGen);
    }

    return codeGen;
  }

  @Override
  protected EasyEntityQuery easyEntityQuery() {
    return easyEntityQuery;
  }

  private void fillCodeGen(CodeGenUpdateReq updateReq, CodeGen codeGen) {
    if (updateReq == null) {
      codeGen.setBasePackage(codegenProps.getBasePackage());
      codeGen.setSourceDir(codegenProps.getSourceDir());
      codeGen.setUiSourceDir(codegenProps.getUiSourceDir());
    } else {
      codeGen.setSourceDir(updateReq.getTable().getSourceDir());
      codeGen.setBasePackage(updateReq.getTable().getBasePackage());
      codeGen.setUiSourceDir(updateReq.getTable().getUiSourceDir());
      codeGen.setAuthor(updateReq.getTable().getAuthor());
    }
  }
}
